package com.nicefact.mailmonitor.service;


import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;

@Service
public class AppFileService {
	
	public String saveFileToBlobStore(String data, String fileName)
			throws IOException {
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile aeF = fileService.createNewBlobFile("text/csv;charset=utf-8", fileName);
		FileWriteChannel writeChannel = (FileWriteChannel) fileService
				.openWriteChannel(aeF, true);
		BufferedOutputStream bos = new BufferedOutputStream(
				Channels.newOutputStream(writeChannel));
		bos.write(data.getBytes());
		bos.flush();
		bos.close();
		writeChannel.closeFinally();
		String blobKey = fileService.getBlobKey(aeF).getKeyString();
		return blobKey;
	}
	
	public byte[] getBytesFromBlob(String blobKeyStr) {
		byte[] ob = null;
		if (!StringUtils.isBlank(blobKeyStr)) {
			BlobstoreService blobstoreService = BlobstoreServiceFactory
					.getBlobstoreService();

			BlobKey blobKey = new BlobKey(blobKeyStr);
			BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
			
			ob= blobstoreService.fetchData(blobKey, 0, new Long(
					blobInfo.getSize()));
		}
		return ob;
	}
	public String getStringFromBlob(String blobKeyStr) {
		String returnStr = "Calculating . Please check after some time";
		if (!StringUtils.isBlank(blobKeyStr)) {
			BlobstoreService blobstoreService = BlobstoreServiceFactory
					.getBlobstoreService();

			BlobKey blobKey = new BlobKey(blobKeyStr);
			BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
			
			byte[] ob = blobstoreService.fetchData(blobKey, 0, new Long(
					blobInfo.getSize()));
			returnStr = new String(ob) ;
			returnStr += ", Last Updated On : " + blobInfo.getCreation().toString();
			System.out.println(returnStr);
		}
		return returnStr;

	}
}
